const fs = require("fs");
const path = require("path");
const qiniu = require("qiniu");
const SystemErrException = require("../exception/systemError");
const awaitWriteStream = require("await-stream-ready").write;
const sendToWormhole = require("stream-wormhole");
const md5 = require("md5");
const bucketName = "waterpaper"; //要上传的空间名
const accessKey = "_mKfxOtH3XySbP5LiurdrQ7DgJ-rZQLow92DaQ4O"; // Access Key
const secretKey = "a6VVlwx4W4xLfKrKzE1GCRR-wt02TfPMZSCrauWk"; // Secret Key
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
  scope: bucketName
};
const putPolicy = new qiniu.rs.PutPolicy(options);

let config = new qiniu.conf.Config();
config.zone = qiniu.zone.Zone_z2;

const bucketManager = new qiniu.rs.BucketManager(mac, config);

const uploadImg = async function (stream) {
  const uploadToken = putPolicy.uploadToken(mac);
  const filename = 'super-' + md5(new Date().getTime()) + path.extname(stream.filename).toLocaleLowerCase();
  const localFilePath = path.join(__dirname, "../public/imgs", filename);
  const writeStream = fs.createWriteStream(localFilePath);
  try {
    await awaitWriteStream(stream.pipe(writeStream));
    const formUploader = new qiniu.form_up.FormUploader(config);
    const putExtra = new qiniu.form_up.PutExtra();
    console.log('图片上传中...');
    const imgPath = await new Promise((resolve, reject) => {
      formUploader.putFile(
        uploadToken,
        filename,
        localFilePath,
        putExtra,
        (respErr, respBody, respInfo) => {
          if (respBody.key && respInfo.statusCode == 200) {
            console.log('图片上传...成功...');
            resolve(respBody.key);
          } else {
            console.log('图片上传...失败...');
            reject(respErr);
          }
          // 上传之后删除本地文件  
          fs.unlinkSync(localFilePath);
        }
      );
    });
    return imgPath;
  } catch (err) {
    console.log('文件上传失败：', err)
    //如果出现错误，关闭管道
    await sendToWormhole(stream);
    throw new SystemErrException("文件上传失败：" + error);
  }
}

const deleteImg = async function (id) {
  try {
    console.log('正在删除文件：', id)
    await new Promise((resolve, reject) => {
      bucketManager.delete(
        bucketName,
        id,
        (respErr, respBody, respInfo) => {
          if (respBody?.error && respBody.error != 'no such file or directory') {
            reject(respBody.error);
          } else {
            resolve({
              massage: '删除成功！'
            });
          }
        }
      );
    })
  } catch (error) {
    throw new SystemErrException("文件删除异常：" + error);
  }
}

const batchDeleteImg = async function (ids) {
  try {
    console.log('正在批量删除图片：', ids)
    const deleteOperations = ids.map(id => {
      return qiniu.rs.deleteOp(bucketName, id);
    })
    console.log(deleteOperations)
    await new Promise((resolve, reject) => {
      bucketManager.batch(
        deleteOperations,
        (respErr, respBody, respInfo) => {
          if (respBody?.error) {
            reject(respBody.error);
          } else {
            resolve({
              massage: '删除成功！'
            });
          }
        }
      );
    })
  } catch (error) {
    throw new SystemErrException("文件删除异常：" + error);
  }
}

module.exports = {
  uploadImg,
  deleteImg,
  batchDeleteImg
};  